<template>
     
    <div style="width:100%;display: flex;justify-content: center;">
    <div class="container" style="margin:20px 20px;width:100%">
        <div class="jumbotron"  v-show="imgurl" :style="{ backgroundImage: 'url('+imgurl+')',backgroundSize: 'cover',backgroundRepeat: 'no-repeat',backgroundPosition: 'center'}">
        </div>
        <div class="d-flex justify-content-center align-items-center "  v-show="!imgurl" style="height: 100px;background-color:#fff;">
                <h1>{{_data.title}}</h1>
            </div>
        <div id="content" style="background-color:#fff;margin-top: 10px;">     
        <ul class="list-group" v-for="(item1,value) in datas" :key="value" style="margin:10px 0" :id="`answer${value}`">
            <radioview :datalist="item1" :questionnaireId="questionnaireId" @ontest="ontest" v-if="item1.type==1"></radioview>
            <checkboxview :datalist="item1"  :questionnaireId="questionnaireId" @ontest="ontest" v-if="item1.type==2"></checkboxview>
            <shortanswerview :datalist="item1"  :questionnaireId="questionnaireId" @ontest="ontest" v-if="item1.type==3"></shortanswerview>     
        </ul>

</div>

<div style="display: flex;justify-content: center;"> <a class="btn btn-primary btn-lg" role="button" @click="submit()">
            提交</a></div>
       
    </div>
    </div>

  </template>
  <script setup>
  import axios from 'axios'
  // vue
  import { reactive, onMounted } from 'vue'
  // 注意路径！！！
  import $tools from '@/assets/tools.js'
  // data
  const _data = reactive({
    // 分享标题、描述、图标等数据(根据您的需求自定义即可)
    info: {
    title: '净月区法院研学反馈问卷',
    desc: '吉报融媒小山小水系列活动',
    cover: 'http://inquire.jlrbyy.cn/dby/img/logo.png',
    // ...
  }
  })
  
  // onMounted
  onMounted(() => {
    // 一键开启页面分享功能
    datalist()
 
    document.title = '调查问卷';
  })
  const datalist=()=>{
          service.get('/prod-api/system/api/questionnaire/getQuestionnaire?questionnaireId='+getUrlCode('sid')).then(response => {    
            console.log(response)   
            //标题 副标题  分享标题 分享简介 分享图片地址  
            _data.title=response.data.title
            _data.desc=response.data.subTitle //副标题
            _data.info.title=response.data.shareTitle
            _data.info.desc=response.data.shareContent || ''
            _data.info.cover=response.data.shareImgUrl || 'http://inquire.jlrbyy.cn/dby/img/logo.png'
            console.log(_data)
            getConfig()
            }).catch(function (error) {
                console.log(error);
            });
        }
const   getUrlCode=(variable) =>{
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
          return pair[1];
        }
      }
      return (false);
    }





  /**
  * 获取配置信息(尽量在mounted()钩子中执行)
  * @description 拿到后端数据后,传入封装好的函数中进行验证
  * @return void
  */
  const getConfig = () => {
    // 请自行替换接口请求方式与地址！！
    axios(`http://inquire.jlrbyy.cn/prod-api/system/api/client/getShareCode`).then(res => {
      console.log('配置信息', res.data)
      // 1: 注入并验证信息
      $tools.config(res.data.data)
      // 2: 调用分享功能
      setShare()
    })
  }
  
  /**
  * 获取配置信息(尽量在mounted()钩子中执行)
  * @description 拿到后端数据后,传入封装好的函数中进行验证
  * @return void
  */
  const setShare = () => {
    // 分享标题、描述、图标等数据(根据您的需求自定义即可)
    const data = _data.info;
    // "分享给朋友/分享到QQ"
    const appMessage = {
      title: data.title, //分享标题
      desc: data.desc, //分享描述
      link:'http://inquire.jlrbyy.cn/dby/',  //location.href, //分享链接,默认当前页面(必须对应JS安全域名)
      imgUrl: data.cover, //分享图标
      success: () => {//调用成功
        // alert('成功')
      },
      fail: (err) => {//调用失败
        alert(JSON.stringify(err))
      }
    }
    // "分享到朋友圈/分享到QQ空间"
    const timeLine = {
      title: data.title, //分享标题
      link: 'http://inquire.jlrbyy.cn/dby/',  //location.href //分享链接,默认当前页面(必须对应JS安全域名)
      imgUrl: data.cover, //分享图标
      success: () => {//调用成功
        // alert('成功')
      },
      fail: (err) => {//调用失败
        alert(JSON.stringify(err))
      }
    }
    // 丢入自动设置
    $tools.wxShare(appMessage, timeLine)
  }
  </script>
  <script>
  import RadioView from '@/components/RadioView.vue';
  import CheckboxView from '@/components/CheckboxView.vue';
  import ShortanswerView from '@/components/Shortanswer.vue';

  import service from '@/utils/request';
import { setTimeout } from 'core-js';
  export default {
  components: {   'radioview': RadioView,
    'checkboxview': CheckboxView,
    'shortanswerview':ShortanswerView,
   },
   beforeCreate: function () {
    // 执行在实例完全创建之前需要的操作
    var ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) === 'micromessenger') {
    console.log('是微信浏览器1')
    return true;
  } else {
    console.log('不是微信浏览器1')
    return false;
  }

  },
    data(){
        return{
        xd:[],
        obj1:{},
        datas:[],
        questionnaireId:'',
        imgurl:'',
        isLoading:true
        }
    },
    created() {
      this.datalist()
  },
  mounted(){
    setTimeout(()=>{
      this.isLoading=false
    },2000)
  },



    methods:{
      getUrlCode(variable) {
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
          return pair[1];
        }
      }
      return (false);
    },
        ontest(idx) {
          console.log(idx)
          this.xd=  this.xd.filter(item => item.questionId !== idx.questionId);
            this.xd.push(idx)
      // 将proxy对象转成 普通数组

            console.log(this.xd)
       },
       datalist:function(e=1){
          service.get('/prod-api/system/api/questionnaire/getQuestionnaire?questionnaireId='+ this.getUrlCode('sid')).then(response => {    
            console.log('AAA======>',response)     
              this.datas=response.data.questionList
              this.questionnaireId=response.data.questionnaireId
              this.imgurl=response.data.imgUrl
        
            }).catch(function (error) {
                console.log(error);
            });
        },
        submit:function(){
          let userInfo=   JSON.parse(localStorage.getItem("userinfo"))
          if(userInfo===null)
          {

          }
          else
          {
          this.obj1={userId:userInfo.userId,openid:userInfo.openId,questionnaireId:this.questionnaireId}
          this.obj1.result=this.xd
          console.log('=======',JSON.stringify(this.obj1))
          try {  
                  const response =  axios.post('/prod-api/system/api/questionnaire/setAnswers',this.obj1);  
                  response.then((msg)=>{
                    console.log(msg)
                    if(msg.data.code==200)
                  {
                    alert('提交成功')
    setTimeout(() => {
      this.$router.push({
      path: "/",
      query: {
        content: JSON.stringify({ id: this.userid }),
      },
    });
    }, 1500);
 
                  } 
                  else
                  {
                    alert('提交失败')
                  }
                  })
   
        
                  } catch (error) {  
                  console.error('Error sending POST request:', error);  
                  }  
          } 
}
    },   
    name: 'List',
    computed:{
        
}
  }
  </script>
  
  <!-- Add "scoped" attribute to limit CSS to this component only -->
  <style >
  .cl{
    display: flex;
  }
  </style>
  